<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title>数据源管理</title>
    <meta name="renderer" content="webkit|ie-comp|ie-stand">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport"
          content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=0">
    <meta http-equiv="Cache-Control" content="no-siteapp"/>
    <script src="/style/public/publicStyle.js"></script>
</head>
<script type="text/html" id="op">
    <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="showDetail">详情</a>
</script>
<body>

<div class="layui-tab-item layui-show">
    <!--表格-->
    <div class="weadmin-body" style="margin-top: 10px">
        <div class="layui-row">
            <div class="layui-col-md5">
                <div class="layui-row" id="tableForm">
                    <div class="layui-col-md12">
                        <input type="hidden" name="idBase"/>
                        <form class="layui-form" action="">
                            <div class="layui-form-item">
                                <div class="layui-row">
                                    <div class="layui-col-md6">
                                        <label class="layui-form-label">开始时间</label>
                                        <div class="layui-input-block">
                                            <input type="text" class="layui-input" id="startDate"
                                                   name="startDate"/>
                                        </div>
                                    </div>
                                    <div class="layui-col-md6">
                                        <label class="layui-form-label">结束时间</label>
                                        <div class="layui-input-block">
                                            <input type="text" class="layui-input" id="endDate" name="endDate"/>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <div class="layui-row">
                                <div class="layui-col-md8">
                                    <label class="layui-form-label">任务类型</label>
                                    <div class="layui-input-block">
                                        <select name="jobType" id="jobTypeSelect" lay-filter="radioCc" ></select>
                                    </div>
                                    <!--<div class="layui-input-block">
                                        <input lay-filter="radioCc" type="radio" name="jobType" value="ODS"
                                               class="jobTypeRadio"
                                               title="ODS" checked>
                                        <input lay-filter="radioCc" type="radio" name="jobType" value="DIM"
                                               class="jobTypeRadio"
                                               title="DIM">
                                        <input lay-filter="radioCc" type="radio" name="jobType" value="DW"
                                               class="jobTypeRadio"
                                               title="DW">
                                        <input lay-filter="radioCc" type="radio" name="jobType" value="DM"
                                               class="jobTypeRadio"
                                               title="DM">
                                    </div>-->
                                </div>
                                <div class="layui-col-md4">
                                    <div class="layui-input-block">
                                        <button id="taskExec" type="button" class="layui-btn  layui-btn-normal ">执行
                                        </button>
                                    </div>
                                </div>
                            </div>

                            <div class="layui-form-item">
                                <div class="layui-row">
                                    <div class="layui-col-md12">
                                        <table class="layui-hide" id="tableDataList"
                                               lay-filter="mainTableFilter"></table>
                                    </div>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
            <div class="layui-col-md1">
                <div style="float:left;width: 1px;height: 800px; background: darkgray;margin-left:20px"></div>
            </div>
            <div class="layui-col-md6">
                <div class="layui-row">
                    显示当前执行/等待中的任务与最近30条手工执行的任务
                    <button id="showTaskExecStatus" type="button" class="layui-btn  layui-btn-normal "
                            style="float: right;">刷新
                    </button>
                    <div class="layui-form-item">
                        <div class="layui-row">
                            <div class="layui-col-md12">
                                <table class="layui-hide" id="tableExecList"
                                       lay-filter="tableExecList"></table>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="layui-collapse" lay-filter="test" id="showDetail" style="display:none;">
    </div>


</div>


</body>

<script>
    var status;

    layui.use(['util', 'laydate', 'laypage', 'layer', 'table', 'carousel', 'upload', 'element'], function () {
        var util = layui.util;
        var laydate = layui.laydate //日期
            , laypage = layui.laypage //分页
            , layer = layui.layer //弹层
            , table = layui.table //表格
            , carousel = layui.carousel //轮播
            , upload = layui.upload //上传
            , element = layui.element //元素操作
            , form = layui.form;


        layui.$('#showTaskExecStatus').on('click', function () {
            table.reload("tableExecList", {where: {jobType: $("#jobTypeSelect").val()}});

        });
        layui.$('#taskExec').on('click', function () {
            var checkStatus = table.checkStatus('tableDataList');

            console.log(checkStatus);

            var ids = "";
            for (let i = 0; i < checkStatus.data.length; i++) {
                ids = ids + "," + checkStatus.data[i].idTask;
            }
            var pram = {};
            var jobType = $("#jobTypeSelect").val();
            pram.endDate = $("#endDate").val();
            pram.startDate = $("#startDate").val();
            pram.idTasks = ids;
            pram.type = jobType;
            if(jobType=="XXL-JOB") {
                $.ajax({
                    url: '/task/jobExec/jobExecByHand',
                    type: 'get',
                    data: pram,
                    success: function (data1) {
                        layer.alert(data1.msg);
                        table.reload("tableExecList", {where: {jobType: $("#jobTypeSelect").val()}});
                    }
                });
            } else {
                $.ajax({
                    url: '/etl/runJob/jobExecByHand',
                    type: 'get',
                    data: pram,
                    success: function (data1) {
                        layer.alert(data1.msg);
                        table.reload("tableExecList", {where: {jobType: $("#jobTypeSelect").val()}});
                    }
                });
            }

        });

        form.on('select(radioCc)', function (data) {
            table.reload("tableDataList", {where: {jobType: data.value}});
            table.reload("tableExecList", {where: {jobType: data.value}});
        })

        laydate.render({
            elem: '#endDate' //指定元素
        });
        laydate.render({
            elem: '#startDate' //指定元素
        });

        $.ajax({
            url: '/med/baseSdItem/findByCdSd',
            type: 'get',
            data: {'cdSd': 'handler_jobType'},
            contentType: 'application/json;charset=UTF-8',
            success: function (data1) {
                var data = data1.data; //提出返回数据中的data
                $("#jobTypeSelect").empty();//清空默认值
                if (data !== null) {
                    var flag = true;
                    $.each(data, function (index, item) { //循环加入 data的元素
                        $("#jobTypeSelect").append("<option value='" + item.cd + "'>" + item.na + "</option>");
                    });
                    form.render("select");
                    table.reload("tableDataList", {where: {jobType: $("#jobTypeSelect").val()}});
                    table.reload("tableExecList", {where: {jobType: $("#jobTypeSelect").val()}});
                }
            }
        });
        table.render({
            elem: '#tableDataList'
            , even: false //开启隔行背景
            , id: 'tableDataList'
            , url: global_visit_url_prefix + '/task/jobExec/findTaskList'
            , where: {jobType: $("input[type='radio']:checked").val()}
            , cols: [[
                {type: 'checkbox'}
                , {field: 'idTask', title: 'ID', hide: true}
                , {field: 'tbTar', title: '目标表'}
                , {field: 'naTask', title: '名称'}
                , {field: 'des', title: '描述'}
                , {field: 'naDbSou', title: '数据源'}

            ]]
            , page: true
        });

        /* table.reload*/
        table.render({
            elem: '#tableExecList'
            , even: false //开启隔行背景
            , id: 'tableExecList'
            , url: '/etl/runJob/findHandlerExec'
            , where: {jobType: $("#jobTypeSelect").val()}
            , cols: [[
                , {field: 'idHandlerExec', title: 'ID', hide: true}
                , {field: 'idGroup', title: '分组', hide: true}
                , {
                    field: 'des', title: '名称'
                }
                , { field: 'dtBegin', title: '开始时间', width: 140, templet: '<div>{{layui.util.toDateString(d.dtBegin, \'MM-dd HH:mm:ss\')}}</div>'}
                //, { field: 'dtEnd', title: '结束时间', width: 140, templet: '<div>{{layui.util.toDateString(d.dtEnd, \'MM-dd HH:mm:ss\')}}</div>' }
                , {field: 'times', title: '耗时(s)', width: 93}
                , {
                    field: 'status', title: '状态', templet: function (d) {
                        return getJobSatus(d)
                    }
                    , width: 73
                }
                , {fixed: 'right', title: '操作', align: 'center', toolbar: '#op', width: 69}
            ]]
            , done: function (res, curr, count) {
                status = res.data;
            }
        });



        table.on('tool(tableExecList)', function (obj) {
            var item = obj.data;
            if (obj.event === 'showDetail') {
                $.ajax({
                    url: '/job/etlGroupBatch/findJobExecutionByIdGroup',
                    type: 'get',
                    data: {"idGroup":item.idGroup},
                    success: function (data1) {
                        var data = data1.data;
                        var html = "";
                        $.each(data,function (index,item) {
                            html += '<div class="layui-colla-item">\n' +
                                '    <h2 class="layui-colla-title" style="'+(item.status=="COMPLETED"?"":"color:red")+'" idJobException="'+item.id+'">'+item.tableName+':'+item.status+'('+item.startDate+'~'+item.endDate+' 累计耗时'+item.times+'秒)'+'</h2>\n' +
                                '    <div class="layui-colla-content">\n' +
                                '      <p>'+item.errorMsg+'</p>\n' +
                                '      <table class="layui-table" name="stepTable"><thead><tr><th>步骤名称</th><th>状态</th><th>读取条数</th><th>写入条数</th><th>跳过条数</th></tr></thead><tbody></tbody></table>\n' +
                                '    </div>\n' +
                                '  </div>';
                        });
                        $("#showDetail").html(html);
                        element.render();
                        layer.open({
                            //layer提供了5种层类型。可传入的值有：0（信息框，默认）1（页面层）2（iframe层）3（加载层）4（tips层）
                            type: 1,
                            title: item.des,
                            area: ['1024px', '700px'],
                            content: $("#showDetail")//引用的弹出层的页面层的方式加载修改界面表单
                        });
                    }
                });

            }
        });

        //监听折叠
        element.on('collapse(test)', function(data){
            var tbody = $(this).parent().find("table[name='stepTable']").find("tbody");
            if(tbody.html()!="") {
                return ;
            }
            var html="";
            $.ajax({
                url: '/job/etlGroupBatch/findStepExecutionByIdJob',
                type: 'get',
                async: false,
                data: {"idJobException":$(this).attr("idJobException")},
                success: function (data1) {
                    var data = data1.data;
                    $.each(data,function (index,item) {
                        html+="<tr><td>"+item.stepName+"</td><td>"+item.status+"</td><td>"+item.readCount+"</td><td>"+item.writeCount+"</td><td>"+item.skipCount+"</td></tr>"
                    });
                    $(this).parent().find("table[name='stepTable']").find("tbody").html(html);
                }
            });
            tbody.html(html);
        });

        function timeFn(dateBegin, dateEnd) {
            var dateDiff = dateEnd - dateBegin;//时间差的毫秒数
            var dayDiff = Math.floor(dateDiff / (24 * 3600 * 1000));//计算出相差天数
            var leave1 = dateDiff % (24 * 3600 * 1000)    //计算天数后剩余的毫秒数
            var hours = Math.floor(leave1 / (3600 * 1000))//计算出小时数
            //计算相差分钟数
            var leave2 = leave1 % (3600 * 1000)    //计算小时数后剩余的毫秒数
            var minutes = Math.floor(leave2 / (60 * 1000))//计算相差分钟数
            //计算相差秒数
            var leave3 = leave2 % (60 * 1000)      //计算分钟数后剩余的毫秒数
            var seconds = Math.round(leave3 / 1000)

            var leave4 = leave3 % (60 * 1000)      //计算分钟数后剩余的毫秒数
            var minseconds = Math.round(leave4 / 1000)
            var timeFn = dayDiff + "天  " + hours + " 小时  " + minutes + " 分钟  " + seconds + " 秒  " + minseconds + " 毫秒";
            return timeFn;
        }

    });

    function getJobSatus(d) {
        if (d.status == "COMPLETED") {
            return "完成";
        } else if (d.status == "STARTING" || d.status == "STARTED" || d.status == "UNKNOWN") {
            return "进行中";
        } else if (d.status == "STOPPED" || d.status == "STOPPING") {
            return "暂停";
        } else if (d.status == "FAILED") {
            return "失败";
        } else if (d.status == "ABANDONED") {
            return "异常结束";
        }
    }

    function formattime(date) {
        if (date == undefined || date == 'undefined' || date == '') {
            return '';
        }

        var timeStr = date.getFullYear() + "-";
        if (date.getMonth() < 9) { // 月份从0开始的
            timeStr += '0';
        }
        timeStr += date.getMonth() + 1 + "-";
        timeStr += date.getDate() < 10 ? ('0' + date.getDate()) : date.getDate();
        timeStr += ' ';
        timeStr += date.getHours() < 10 ? ('0' + date.getHours()) : date.getHours();
        timeStr += ':';
        timeStr += date.getMinutes() < 10 ? ('0' + date.getMinutes()) : date.getMinutes();
        timeStr += ':';
        timeStr += date.getSeconds() < 10 ? ('0' + date.getSeconds()) : date.getSeconds();
        return timeStr;
    }

    function getjobParameterValue(item, name) {
        if (item == undefined || item == 'undefined' || item == '') {
            return '';
        }
        if (item.jobParameters == undefined || item.jobParameters == 'undefined' || item.jobParameters == '') {
            return '';
        }
        if (item.jobParameters.parameters == undefined || item.jobParameters.parameters == 'undefined' || item.jobParameters.parameters == '') {
            return '';
        }
        var parem = item.jobParameters.parameters[name]

        if (parem == undefined || parem == 'undefined' || parem == '') {
            return '';
        }
        var value = parem.value;
        if (parem == undefined || parem == 'undefined' || parem == '') {
            return '';
        } else {
            return value;
        }
    }

    function toDate(date) {
        if (date == undefined || date == 'undefined' || date == '') {
            return null;
        }
        const s2 = date.replace(/(\+\d{2})(\d{2})$/, "$1:$2");
        const d2 = new Date(s2);
        return d2;
    }
</script>

</html>